Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

  1. Window position Max
  2. --------------- -----
  3. [1 3 -1] -3 5 3 6 7 3
  4. 1 [3 -1 -3] 5 3 6 7 3
  5. 1 3 [-1 -3 5] 3 6 7 5
  6. 1 3 -1 [-3 5 3] 6 7 5
  7. 1 3 -1 -3 [5 3 6] 7 6
  8. 1 3 -1 -3 5 [3 6 7] 7

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note:

You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:

Could you solve it in linear time?

Hint:

  1. How about using a data structure such as deque (double-ended queue)?
  2. The queue size need not be the same as the window’s size.
  3. Remove redundant elements and the queue should store only elements that need to be considered.

Solution:

  1. public class Solution {
  2. public int[] maxSlidingWindow(int[] nums, int w) {
  3. if (nums == null || nums.length == 0 || w < 1)
  4. return new int[0];
  5. int n = nums.length, k = 0;
  6. int[] res = new int[n - w + 1];
  7. // use a deque to control the window
  8. Deque<Integer> q = new ArrayDeque<Integer>();
  9. for (int i = 0; i < n; i++) {
  10. // exceeds window size
  11. if (!q.isEmpty() && q.peekFirst() + w <= i)
  12. q.removeFirst();
  13. // pop those smaller ones from behind
  14. while (!q.isEmpty() && nums[q.peekLast()] <= nums[i])
  15. q.removeLast();
  16. q.addLast(i);
  17. if (i >= w - 1)
  18. res[k++] = nums[q.peekFirst()];
  19. }
  20. return res;
  21. }
  22. }